#include "main.h"

void ctrl_a9(char data)
{
	key_desc key2;
	char buf = data;
	
	switch (buf)
	{
		case 0x11:
			printf("led2_on\n");
			key2.num = 2;
			key2.flag = 1;
			ioctl(A9_fd,KEY_CTL,&key2);
			break;
		case 0x10:
			printf("led2_off\n");
			key2.num = 2;
			key2.flag = 0;
			ioctl(A9_fd,KEY_CTL,&key2);
			break;
		case 0x22:
			printf("led3_on\n");
			key2.num = 3;
			key2.flag = 1;
			ioctl(A9_fd,KEY_CTL,&key2);
			break;
		case 0x20:
			printf("led3_off\n");
			key2.num = 3;
			key2.flag = 0;
			ioctl(A9_fd,KEY_CTL,&key2);
			break;
		case 0x1:
			key2.num = 4;
			key2.flag = 1;
			ioctl(A9_fd,KEY_CTL,&key2);
			break;
		case 0x0:
			key2.num = 4;
			key2.flag = 0;
			ioctl(A9_fd,KEY_CTL,&key2);
			break;
		default:
			break;
	}
}

int ctrl_M0(char data)
{
	char buf = data;
	printf("%#x\n",buf);
	if(write(dev_uart_fd, &buf, sizeof(buf)) == -1)
		return -1;
	return 0;
}

int pthread_write(void * arg)
{
	key_t key; 
	int msgid;
	struct msg msg_buf = {0, 0, {0}};
	
#if 1
	if((key = ftok("/app", 'g')) < 0)
	{
		perror("ftok\n");
		exit(1);
	}
	if((msgid = msgget(key,IPC_CREAT|IPC_EXCL|0666)) < 0)
	{
		if(errno == EEXIST)
			msgid = msgget(key,0666);
		else
		{
			perror("msgget\n");
			exit(1);
		}
	}

	if((A9_fd = open("/dev/key2",O_RDWR)) < 0)
	{
		perror("open faile\n");
		return -1;	
	}

#endif

	while(1)
	{
		if((msgrcv(msgid, &msg_buf, sizeof(msg_buf)-sizeof(long), 1,0)) > 0)
		{
			switch (msg_buf.msgtype)
			{
				case 1L:
					ctrl_a9(msg_buf.text[0]);
					break;
				case 2L:
					ctrl_a9(msg_buf.text[0]);
					break;
				case 4L:
					ctrl_M0(msg_buf.text[0]);
					break;
				default:
					
				break;	
			}
	
		}
		memset(&msg_buf, 0, sizeof(msg_buf));		
	}
	return 0;
}
